package com.concurrent.sample.business.config;

import com.concurrent.sample.business.consts.BusinessRedisCacheConsts;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class SysConfig implements ApplicationRunner {

  /**
   * 包装服务器获取到的 ID 是唯一的
   */
  public long serviceId;

  private final RedissonClient redissonClient;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    RAtomicLong atomicLong = redissonClient.getAtomicLong(BusinessRedisCacheConsts.SERVICE_ID_KEY);
    serviceId = atomicLong.incrementAndGet();
    log.info("system get service id = {}", serviceId);
  }

  public String buildThreadKey(long threadId){
    return serviceId + "_" + threadId;
  }

  public boolean matchThread(long threadId, String threadKey){
    return Objects.equals(buildThreadKey(threadId), threadKey);
  }

}
